Grokking Python Fundamentals
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Course Overview
Python Basics
Python Overview
Python Application Areas
Your First Python Program
Python - Basic Syntax
Python Comments
Quiz
Python Variables and Operators
Python - Variables
Python - Data types
Python - Numbers
Python - Booleans
Python - Type Conversions
Python - Operators
Quiz
Python Conditionals
Introduction to Conditional Statements in Python
Python - If...Else
Python - Match Case
Quiz
Python loops
Introduction to loops in Python
Python - for loop
Python - while loop
Python - Loop Control
Python - for else and while else loop
Quiz
Python Strings
Introduction to Strings in Python
Python - String Operators
Python Slicing Strings
Python - String Methods
Quiz
Introduction to Array in Python
Python - Array Methods
Quiz
Introduction to Lists in Python
Python - Add and Remove List Items
Python - List Comprehension
Python - List Methods
Quiz
Introduction to Tuple in Python
Python - Unpack Tuple Items
Python - Join Tuples
Python - Tuple Methods
Quiz
Introduction to Dictionary in Python
Python - Nested Dictionaries
Python - Dictionary Methods
Quiz
Introduction to set in Python
Python - set Operations
Python - Set Methods
Quiz
Introductions to Function in Python
Python - Function Arguments
Recursive Functions
Python - Variable scope
Importing Modules
Quiz
Introduction to Strings in Python

Strings in Python are sequences of characters and are among the most widely used data types.

Strings are immutable, which means that once a string is created, its characters cannot be modified directly. This property ensures that strings can be passed around safely in a program without altering the original data. Python treats single characters as strings of length one, making it consistent in handling textual data. Various operations such as slicing, concatenating, and formatting are available, allowing for robust manipulation of text data.

Creating a String

Strings in Python can be created using single quotes, double quotes, or triple quotes for multiline strings. This flexibility allows for easy handling of text data in various scenarios:

  • Single quotes: Ideal for most strings, and helps in avoiding issues with special characters like the double quote.
  • Double quotes: Useful when the string itself contains single quotes/apostrophes.
  • Triple quotes: Best for creating multiline strings and strings that contain both single and double quotes.
Image

Example

In the following example, we will define strings using different types of quotes and print them:

Python3

. . . .

Explanation:

  • single_quote_string is encapsulated within single quotes, suitable for simple strings.
  • double_quote_string uses double quotes to incorporate an apostrophe, demonstrating the utility of double quotes in such cases.
  • multiline_string uses triple quotes to span multiple lines and include both single and double quotes, showing how triple quotes can be useful for complex strings.

Accessing String Characters and Understanding String Indexing

String indexing in Python is a powerful feature that allows you to access individual characters in a string. Python supports both positive and negative indexing.

  • Positive Indexing: Begins at the start of the string with the index 0 for the first character, 1 for the second, and so on.
  • Negative Indexing: Starts at the end of the string with the index -1 for the last character, -2 for the second-last, and continues similarly towards the start of the string.
Image

Example

Here, we demonstrate how to access characters from a given string using both positive and negative indexing, and we'll print the outputs to illustrate:

Python3

. . . .

Explanation:

  • phrase[7]: Accesses the eighth character using positive indexing, which is 'p' in "Python programming is fun!".
  • phrase[-4]: Accesses the fourth character from the end using negative indexing, which is 'f' in the same string.
  • first_char = phrase[0]: Retrieves 'P', the very first character, demonstrating positive indexing starting at zero.
  • last_char = phrase[-1]: Retrieves '!', the last character, showcasing negative indexing starting from the end.

Updating Strings in Python

In Python, strings are immutable, which means that once a string is created, its characters cannot be changed individually. However, you can create new strings based on existing ones by combining slicing and concatenation techniques, effectively 'updating' a string by creating a modified version of it.

Example

Here's how you can modify a string by creating a new one through concatenation and slicing:

Python3

. . . .

Explanation:

  • original_string[:7]: This slices the original string from the beginning to the position before index 7, extracting "Hello, ".
  • Concatenating "Python!": The string "Python!" is added to the end of the sliced string, resulting in a new string "Hello, Python!".
  • This method does not change the original string but instead creates a new string with the desired modifications.

Concatenating Strings in Python

Concatenation is the process of joining two or more strings into a single one. In Python, this can be done using the + operator or the join() method for more complex operations.

Example

Let's demonstrate simple string concatenation and using join() for combining multiple strings:

Python3

. . . .

Explanation:

  • greeting + ", " + name + "!": Concatenates several strings and commas to form a greeting message.
  • " ".join(words): The join() method is used here to concatenate all elements in the list words, separated by spaces. This is useful for more complex concatenations where elements are in an iterable like a list.

String Formatting in Python

String formatting allows for creating more complex and dynamically generated strings. Python provides several methods for formatting strings, including the older % formatting, the str.format() method, and f-strings (formatted string literals) introduced in Python 3.6.

Example

Here's how to format strings using f-strings, which provide a very readable and concise way to include expressions inside string literals:

Python3

. . . .

Explanation:

  • f"{name} is {age} years old.": The f-string format allows you to embed expressions inside string literals directly. Variables name and age are inserted directly into the string, making the code very clean and readable.

Looping Through Strings

Looping through strings involves accessing each character in the string one at a time. This can be done using a for loop, which iterates over each character in the string.

Example

Here we will loop through a string and print each character:

Python3

. . . .

Explanation:

  • for character in "Hello, world!":: This loop iterates over each character in the string. The character variable takes the value of each character sequentially from the string "Hello, world!".
  • print(character, end=' '): Prints each character followed by a space instead of the default newline.

Python - Escape Characters

Escape characters in Python are used to perform specific actions within strings that would otherwise be difficult or impossible to represent. These characters are prefixed with a backslash (\) and are essential when you need to include special characters in a string, like newlines, tabs, or quotes.

Understanding escape characters is crucial for formatting output correctly, creating strings that include special characters, and writing code that interacts seamlessly with various data formats and systems.

Escape Characters

Here is a table of common escape characters in Python, each with a description and example:

Escape CharacterDescriptionExample Usage
\\Backslash"This is a backslash \\\\"
\'Single quote'It\'s a single quote'
\"Double quote"He said, \"Hello\""
\nNewline"First line\nSecond line"
\tHorizontal tab"Column 1\tColumn 2"
\rCarriage return"Hello\rWorld"
\bBackspace"ABC\b"
\fForm feed"Page\fNew page"
\oooCharacter with octal value ooo"\101" (A)
\xhhCharacter with hex value hh"\x41" (A)

This lesson covers essential techniques for working with strings in Python, from modifying and combining strings to formatting and iterating over them. Each technique has unique applications and is critical for effective string manipulation in Python programming.

Quiz
Python - String Operators
Mark as Completed

On this page

Creating a String

Example

Accessing String Characters and Understanding String Indexing

Example

Updating Strings in Python

Example

Concatenating Strings in Python

Example

String Formatting in Python

Example

Looping Through Strings

Example

Python - Escape Characters

Escape Characters